from django.contrib.auth import authenticate, login
from django.db import DatabaseError
from django.shortcuts import render, redirect
from django.views import View
from ihome.libs.captcha.captcha import captcha
from django import http
from django_redis import get_redis_connection
import json
import re
import random
from ihome.utils.response_code import RET
from useres.models import User


class ImageCodeView(View):
    def get(self,request):
        uuid = request.GET.get("cur")
        pre = request.GET.get('pre')

        redis_conn = get_redis_connection("code")

        if pre:
            redis_conn.delete("image_code_%s"%pre)

        _,text,image_data = captcha.generate_captcha()

        redis_conn.set("image_code_%s"%uuid,text,60)

        return http.HttpResponse(image_data,content_type="image/png")



class SMSCodeView(View):
    def post(self, request):

        # 1、接收参数
        dict_data = json.loads(request.body.decode())
        mobile = dict_data.get("mobile")
        image_code_id = dict_data.get("id")
        image_code = dict_data.get("text")

        # 2、创建实例redis实例对象
        redis_conn = get_redis_connection('code')

        # 判断该手机号的标记是否存在，如果存在说明发送短信频繁
        sms_code_flag = redis_conn.get("sms_code_flag_%s" % mobile)
        if sms_code_flag:
            return http.JsonResponse({'error': RET.REQERR, 'errmsg': '请求过于频繁'})
        # 2、校验参数
        if not all([mobile, image_code_id, image_code]):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        if not re.match(r"1[35678]\d{9}", mobile):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        try:
            real_image_code = redis_conn.get('image_code_' + image_code_id)
            if not real_image_code:
                return http.JsonResponse({"errno": RET.NODATA, "errmsg": "验证码已经过期"})
            redis_conn.delete('image_code_' + image_code_id)
        except Exception as e:

            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "数据库查询错误"})

        # 因为redis数据库读出的数据是bytes类型，需要decode
        if image_code.upper() != real_image_code.decode().upper():
            return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "验证码输入错误"})

        # 3、生成手机验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print(sms_code)
        # logger.info("短信验证码是:%s" % sms_code)

        # 4、将短信验证码保存到redis
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex("sms_code_flag_%s" % mobile, 300, 1)
        pl.execute()

        # 5、发送短信
        # try:
        #     result = CCP().send_sms_code(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        #     if result != 0:
        #         return http.JsonResponse({"errno": RET.THIRDERR, "errmsg": "第三方系统出错"})
        # except Exception as e:
        #     logger.error(e)
        #     return http.JsonResponse({"errno": RET.UNKOWNERR, "errmsg": "未知错误"})
        # TODO：在考虑选用哪种异步任务实现短信发送

        # 6、返回响应
        return http.JsonResponse({'errno': RET.OK, 'errmsg': '发送短信成功'})

        # def post(self,request):
    #     data_dict = json.loads(request.body.decode())
    #     mobile=data_dict.get("mobile")
    #     imageCode=data_dict.get("text")
    #     imageCodeId=data_dict.get("id")
    #
    #
    #     if not re.match(r'^1[3-9]\d{9}$', mobile):
    #         return http.HttpResponseForbidden("手机号格式有误")
    #
    #     redis_conn = get_redis_connection("code")
    #     redis_image_code = redis_conn.get("image_code_%s" % imageCodeId)
    #
    #     if imageCode != redis_image_code.decode():
    #         return http.HttpResponseForbidden("图片验证码填写错误")
    #
    #     sms_code="%06d"%random.randint(0,999999)
    #     print(sms_code)
    #
    #     # from ihome.celery_tasks.sms.tasks import send_message
    #     # send_message.delay(mobile,sms_code)
    #
    #     # ccp = CCP()
    #     # result = ccp.send_template_sms('mobile', ['sms_code', 5], 1)
    #     # if result == -1:
    #     #     return http.HttpResponseForbidden("短信发送失败")
    #
    #     redis_conn.set("sms_code_%s"%mobile,sms_code,300)
    #
    #     redis_conn.set("send_flag_%s"%mobile,1,60)
    #
    #     return http.JsonResponse({
    #         "errno": "0",
    #         "errmsg": "发送成功"
    #     })
    #
    #     # return redirect('login.html')